/**
 * Created by gongxun on 16/12/11.
 */

var WhmjUILayer = GameCCSBase.extend({

    mWhmjTableResultLayer : null,
    mWhmjControlLayer : null,
    mWhmjSettingLayer : null,
    mWhmjTableCancleJuLayer : null,
    mWhmjTableRecordCardLayer : null,
    mWhmjTableEndLayer : null,
    mWhmjDialogChat : null,
    mWhmjTablePlayerInfoLayer : null,
    mWhmjTableMicLayer : null,
    mKwxApplyTableLayer : null,

    Panel_wait : null,

    Button_invite : null,
    Button_ready : null,
    Button_jiesan : null,


    //用户信息
    mPlayerInfos : null,

    //玩家头像
    Image_players : null,

    //玩家信息
    Panel_playerInfos : null,

    //聊天
    Panel_chats : null,

    //踢人
    Button_kicks : null,


    ctor : function(){
        this._super();
        this.loadCocostudio("res/ccs/WhmjUI.json");
        mo.gameHelper.fixIosText(this.ccsNode);

        this.Panel_wait = mo.seekWidgetByName(this.ccsNode, "Panel_wait");

        this.Button_invite = mo.seekWidgetByName(this.ccsNode, "Button_invite");
        this.Button_ready = mo.seekWidgetByName(this.ccsNode, "Button_ready");
        this.Button_jiesan = mo.seekWidgetByName(this.ccsNode, "Button_jiesan");

        this.mWhmjTableResultLayer = new WhmjTableResultLayer();
        this.addChild(this.mWhmjTableResultLayer);

        this.mWhmjControlLayer = new WhmjControlLayer();
        this.addChild(this.mWhmjControlLayer);

        //个人信息
        this.mWhmjTablePlayerInfoLayer = new WhmjTablePlayerInfoLayer();
        this.addChild(this.mWhmjTablePlayerInfoLayer);

        if (cc.sys.isNative){
            this.mWhmjTableMicLayer = new WhmjTableMicLayer();
            this.addChild(this.mWhmjTableMicLayer);
        }

        //设置
        this.mWhmjSettingLayer = new WhmjSettingLayer();
        this.addChild(this.mWhmjSettingLayer);

        //聊天
        this.mWhmjDialogChat = new WhmjDialogChat();
        this.addChild(this.mWhmjDialogChat);

        //结算
        this.mWhmjTableEndLayer = new WhmjTableEndLayer();
        this.addChild(this.mWhmjTableEndLayer);

        //解散
        // this.mWhmjTableCancleJuLayer = new WhmjTableCancleJuLayer();
        // this.addChild(this.mWhmjTableCancleJuLayer);

        //退出
        this.mKwxApplyTableLayer = new KwxApplyTableLayer("whmj");
        this.addChild(this.mKwxApplyTableLayer);

        this.loadUI();
    },

    onEnter : function(){
        this._super();
        this.reset();

        mo.eventHelper.add("UserChatMsgResponse", this, function(userChatMsgResponse){
            this.setChatMsg(userChatMsgResponse);
        });

        mo.eventHelper.add("UserOnLineChange", this, function(onlineInfo){
            this.setPlayerOnlineStats(onlineInfo);
        });

        //退出
        mo.eventHelper.add("CancleJuRequestwhmj", this, function(cancleJu){
            this.mKwxApplyTableLayer.updateCancelJuInfo(cancleJu);
        });
    },

    onExit : function(){
        mo.eventHelper.remove(this);
        this._super();
    },


    setIsReplay : function(isReplay){
        mo.seekWidgetByName(this.ccsNode, "Button_chat").setVisible(!isReplay);
        mo.seekWidgetByName(this.ccsNode, "Button_setting").setVisible(!isReplay);
        if (this.mWhmjTableMicLayer != null){
            this.mWhmjTableMicLayer.setVisible(!isReplay);
        }
    },

    loadUI : function(){
        //准备
        this.Button_ready.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                mo.gameMsgManager.sendGameReadyRequestwhmj();
            }
        }, this);

        //邀请
        this.Button_invite.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                mo.whmjTabel.onInvite();
            }
        }, this);

        //解散
        this.Button_jiesan.addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {

                var isStart = mo.whmjTabel.mTableConfig.maxpan != mo.whmjTableStatus.mTableStatus.LeftPlayTimes;
                if (!isStart){
                    mo.showMsgDialogOkAndCancel("确定退出房间吗？\n牌局未开始退出不会消耗房卡\n房主退出会解散牌桌", function(){
                        mo.gameMsgManager.sendForceExitTableRequestwhmj();
                    }, this,
                    function(){

                    }, this)
                }

                // if (mo.whmjTabel.mPlayerType == 0){
                //     mo.whmjTabel.mWhmjReplayLayer.onPlayEnd();
                // }else{
                //     mo.whmjTabel.mWhmjUILayer.mWhmjTableCancleJuLayer.sendCancelTableAgree();
                // }
            }
        }, this);


        //聊天
        mo.seekWidgetByName(this.ccsNode, "Button_chat").addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                this.mWhmjDialogChat.setDialog(true);
            }
        }, this);

        //设置
        mo.seekWidgetByName(this.ccsNode, "Button_setting").addTouchEventListener(function(sender, type){
            if (mo.gameHelper.getIsTouchEnd(type)) {
                this.mWhmjSettingLayer.setDialog(true);
            }
        }, this);

        //玩家头像
        this.Image_players = [];
        for (var i = 0; i < 4; i++){
            var Image_player = mo.seekWidgetByName(this.ccsNode, "Image_player" + i);
            this.Image_players.push(Image_player);

            Image_player.setTag(i);
            Image_player.addTouchEventListener(function(sender, type){
                if (mo.gameHelper.getIsTouchEnd(type)) {
                    var index = sender.getTag();
                    var logicSeat = mo.whmjTableStatus.getLogicForView(index, mo.whmjTableStatus.mTableStatus.MySeat - 1) + 1;
                    var seatUser = mo.whmjTableStatus.mTableStatus["SeatUser" + logicSeat];
                    if (seatUser != null){
                        this.mWhmjTablePlayerInfoLayer.showPlayerInfo(index, seatUser.user_info, sender.getPosition(), logicSeat - 1);
                    }
                }
            }, this);

            mo.seekWidgetByName(Image_player, "Image_host").setVisible(false);
            mo.seekWidgetByName(Image_player, "fanshuBg").setVisible(false);
        }


        //聊天
        this.Panel_chats = [];
        for(var i = 0; i < 4; i++){
            var Panel_chat = mo.seekWidgetByName(this.ccsNode, "Panel_chat" + i);
            this.Panel_chats.push(Panel_chat);
            Panel_chat.setVisible(false);
        }

        //玩家信息
        this.Panel_playerInfos = [];
        for(var i = 0; i < 4; i++){
            var Panel_playerInfo = mo.seekWidgetByName(this.ccsNode, "Image_playerInfo" + i);
            this.Panel_playerInfos.push(Panel_playerInfo);
            Panel_playerInfo.setVisible(false);
        }

        //踢人
        this.Button_kicks = [];
        for(var i = 1; i < 4; i++){
            var Button_kick = mo.seekWidgetByName(this.ccsNode, "Button_kick" + i);
            this.Button_kicks.push(Button_kick);
            Button_kick.setVisible(false);
        }
    },

    //重置
    reset : function(){

    },

    //设置够胡
    setHostStatus : function(gouhus, jindings){
        for (var i = 0; i<4; i++) {
            var Image_player = this.Image_players[i];
            mo.seekWidgetByName(Image_player, "fanshuBg").setVisible(true);

            var Image_gouhu =  mo.seekWidgetByName(Image_player, "Image_gouhu");
            Image_gouhu.setVisible(true);
            if(gouhus[i]){
                mo.gameHelper.loadTextureImage(Image_gouhu, "res/ccs/whmj/ui/host/huanggou.png");
            }else{
                mo.gameHelper.loadTextureImage(Image_gouhu, "res/ccs/whmj/ui/host/huigou.png");
            }
        }
    },

    //设置单杠牌 [[0, 1, 2],[],[],[]]
    setSingCards : function (singCardss) {

    },

    //设置番数
    setFanshu : function(fanNums){
        for (var i = 0; i<4; i++) {
            var Image_player = this.Image_players[i];
            mo.seekWidgetByName(Image_player, "fanshuBg").setVisible(true);

            var Text_fanshu =  mo.seekWidgetByName(Image_player, "fanshu");
            Text_fanshu.setVisible(true);
            mo.gameHelper.setTextString(Text_fanshu, fanNums[i] + "番");
        }
    },

    setUserInfos : function(infos){

        var isSeatFull = true;
        this.mPlayerInfos = infos;

        for (var i = 0; i<4; i++){
            var Image_player = this.Image_players[i];
            if(infos[i]){
                Image_player.setVisible(true);

                //head
                mo.gameHelper.loadImageForUrl(mo.seekWidgetByName(Image_player, "Image_head"), infos[i].user_info.faceUrl);

                //nick
                mo.gameHelper.setTextString(mo.seekWidgetByName(Image_player, "Text_nick"), mo.gameHelper.getUserNickFilter(infos[i].user_info.nickname));

                //score
                mo.gameHelper.setTextString(mo.seekWidgetByName(Image_player, "Text_score"), infos[i].Score);

                //online
                //todo


                //是否庄家
                var host_image = mo.seekWidgetByName(Image_player, "Image_host");
                if(infos[i].IsHost){
                    host_image.setVisible(true);
                }else{
                    host_image.setVisible(false);
                }

                //ready
                var Image_ready = mo.seekWidgetByName(Image_player, "Image_ready");
                if (mo.whmjTableStatus.mTableStatus.Step == 0){
                    var isReady = (infos[i].State == 1);
                    Image_ready.setVisible(isReady);

                    if (i == 0){
                        this.Button_ready.setVisible(!isReady);
                    }
                }else{ //开始打牌了
                    Image_ready.setVisible(false);
                    this.Button_ready.setVisible(false);
                }
                //todo 设置番数，是否够胡，金顶，杠的数据等
            }else{
                Image_player.setVisible(false);
                isSeatFull = false;
            }
        }

        this.setPlayerSeatPos(isSeatFull);
    },


    //单杠动画
    singCardAction : function(seat, cradNum){
        var Panel_singCard = mo.seekWidgetByName(this.mHosts[seat], "Panel_singCard");
        Panel_singCard.stopAllActions();

        var Image_gang = mo.seekWidgetByName(Panel_singCard, "Image_gang");

        //如果展开了，就不做动画
        if(!Image_gang.isVisible()){
            return;
        }

        var filename = null;
        if (cradNum == mo.whmjCardHelper.laiziNum){
            filename = "res/ccs/whmj/ui/host/singCard_lai.png";
        }else if(cradNum == 86){
            filename = "res/ccs/whmj/ui/host/singCard_fa.png";
        }else{
            filename = "res/ccs/whmj/ui/host/singCard_zhong.png";
        }
        var Image_singNum = mo.seekWidgetByName(Panel_singCard, "Image_singNum");
        Image_singNum.setScale(1.0);
        Image_singNum.stopAllActions();
        mo.gameHelper.loadTextureImage(Image_singNum, filename);

        Image_singNum.runAction(cc.sequence(
            cc.scaleTo(1.0, 2.0, 2.0),
            cc.scaleTo(1.0, 1.0, 1.0),
            cc.callFunc(function () {
                Image_singNum.loadTexture("singCard_21.png",ccui.Widget.PLIST_TEXTURE);
                Image_singNum.setScale(0.6);
            })
        ));
    },

    setChatMsg : function(userChatMsg){
        var seat = mo.whmjTableStatus.getViewSeatForUid(userChatMsg.uid);
        var Panel_chat = this.Panel_chats[seat];
        Panel_chat.stopAllActions();

        var Image_chat = mo.seekWidgetByName(Panel_chat, "Image_chat");
        var Sprite_face = mo.seekWidgetByName(Panel_chat, "Sprite_face");
        var Panel_audio = mo.seekWidgetByName(Panel_chat, "Panel_audio");
        var Text_content = mo.seekWidgetByName(Panel_chat, "Text_content");

        Panel_chat.setVisible(false);
        Image_chat.setVisible(false);
        Sprite_face.setVisible(false);
        Panel_audio.setVisible(false);
        Text_content.setVisible(false);

        if (userChatMsg.type == 1){
            //处理文字消息
            var numIndex = parseInt(userChatMsg.msg);

            if (numIndex >=0 && numIndex < 11){
                //播放音效
                var sex = mo.whmjTableStatus.getSexForUid(userChatMsg.uid);
                mo.soundHelper.playUserCustom(sex, numIndex);

                //快捷短语
                Text_content.setVisible(true);
                mo.gameHelper.setTextString(Text_content, mo.gameUserInfo.userCustomText[numIndex]);
                var sizeW = Text_content.getContentSize().width + 40;
                sizeW = Math.max(sizeW, 70);
                Text_content.setPositionX(sizeW / 2);

                Panel_chat.setVisible(true);
                Image_chat.setVisible(true);
                Image_chat.setContentSize(cc.size(sizeW, 64));

                Panel_chat.runAction(
                    cc.sequence(
                        cc.delayTime(3.0),
                        cc.hide()
                    )
                );
            }else if (numIndex >= 51 && numIndex < 74){

                //表情
                Sprite_face.setVisible(true);
                var animation = new cc.Animation(mo.whmjCardHelper.getFaceFrames(numIndex - 51));
                animation.setDelayPerUnit(0.2);
                Sprite_face.stopAllActions();
                Sprite_face.runAction(cc.repeatForever(cc.animate(animation)));

                Panel_chat.setVisible(true);

                Panel_chat.runAction(
                    cc.sequence(
                        cc.delayTime(3.0),
                        cc.hide(),
                        cc.callFunc(function(){
                            Sprite_face.stopAllActions();
                        }, Panel_chat)
                    )
                );
            }else{
                var formSeat = seat;
                var toSeat = mo.whmjTableStatus.getViewForLogic(numIndex % 10, mo.whmjTableStatus.mTableStatus.MySeat - 1);
                var index = (parseInt(numIndex / 10) % 10);
                var p1 = this.Image_players[formSeat].getPosition();
                var p2 = this.Image_players[toSeat].getPosition();

                this.mWhmjTablePlayerInfoLayer.showEffectChat(formSeat, toSeat, index, p1, p2);
            }
        }else{
            if (!cc.sys.isNative){
                return;
            }

            //语音
            Panel_audio.setVisible(true);

            Image_chat.setVisible(true);
            Image_chat.setContentSize(cc.size(70, 64));

            //语音信息
            var intArray = [];
            var vmsg = userChatMsg.vmsg;
            var lenght = vmsg.limit - vmsg.offset;
            for (var i = 0; i < lenght; i++){
                intArray.push(vmsg.view[i + vmsg.offset]);
            }

            var millisecond = mo.gameHelper.getMillisecond().toString();
            var fileName = millisecond + ".amr";
            mo.nativeHelper.playFile(fileName, intArray);

            var time = (lenght / 1500);
            Image_chat.runAction(
                cc.sequence(
                    cc.delayTime(time),
                    cc.hide()
                )
            );
        }
    },

    setPlayerSeatPos : function(isSeatFull){
        this.Button_invite.setVisible(!isSeatFull);
    },

    //设置离线状态
    setPlayerOnlineStats : function(onlineInfo){
        //重置
        for (var i = 0; i < 4; i++) {
            var Image_player = this.Image_players[i];
            mo.seekWidgetByName(Image_player, "Image_online").setVisible(false);
        }

        //设置状态
        if (this.mPlayerInfos != null){
            for (var i = 0; i < 4; i++) {
                if (this.mPlayerInfos[i] == null){
                    continue;
                }
                var Image_player = this.Image_players[i];
                var uid = this.mPlayerInfos[i].user_info.userid;

                if (onlineInfo[uid.toString()] != undefined && onlineInfo[uid.toString()] == 0){
                    mo.seekWidgetByName(Image_player, "Image_online").setVisible(true);
                }
            }
        }
    },

    showReady : function(isShow){
        this.Panel_wait.setVisible(isShow);

        var isShowJiesan = mo.whmjTabel.mTableConfig.maxpan == mo.whmjTableStatus.mTableStatus.LeftPlayTimes;
        if (isShow){
            this.Button_jiesan.setVisible(isShowJiesan);
        }
    },


});